package auth.service.Impl;

import auth.service.UserService;
import auth.util.RedisUtil;
import com.woniuxy.common.constant.UserConstant;
import com.woniuxy.common.entity.CenterUser;
import com.woniuxy.common.entity.CenterUserExample;
import com.woniuxy.common.entity.ForumForum;
import com.woniuxy.common.mapper.CenterUserMapper;
import com.woniuxy.common.mapper.ForumForumMapper;
import com.woniuxy.common.utils.KeyUtil;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 登录相关服务
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private CenterUserMapper centerUserMapper;
    @Autowired
    private ForumForumMapper ForumForumMapper;
    @Autowired
    private RedisUtil redisUtil;
    /*
    账号存在验证
     */
    @Override
    public CenterUser findUser(String phone) {
        //检索用户
        CenterUserExample userExample=new CenterUserExample();
        userExample.createCriteria().andPhoneEqualTo(phone);
        List<CenterUser> centerUsers = centerUserMapper.selectByExample(userExample);
        //用户不存在则返回null
        if(centerUsers.size()==0){
            return null;
        }else{
            return centerUsers.get(0);
        }
    }
    /*
    注册
     */
    @Override
    public Map<String, Object> addUser(CenterUser centerUser) {
        System.out.println(centerUser);
        Map<String,Object>result=new HashMap<>();
        result.put("code",200);
        Pattern pattern = Pattern.compile("[0-9]*");
        //手机检查
        if(centerUser.getPhone()==null||centerUser.getPhone().length()!=11||!pattern.matcher(centerUser.getPhone()).matches()){
            result.put("mes","手机为11位数字！");
            result.put("status",0);
            return result;
        }
        //判断是否已注册
        CenterUserExample userExample=new CenterUserExample();
        userExample.createCriteria().andPhoneEqualTo(centerUser.getPhone());
        List<CenterUser> centerUsers = centerUserMapper.selectByExample(userExample);
        if(centerUsers.size()!=0){
            result.put("mes","用户已存在！");
            result.put("status",0);
            return result;
        }
        //昵称检查
        if(centerUser.getNickname()==null||centerUser.getNickname().length()>8||centerUser.getNickname().length()<1){
            result.put("mes","昵称1-8位！");
            result.put("status",0);
            return result;
        }
        //姓名检查
        if(centerUser.getName()==null||centerUser.getName().length()>50||centerUser.getName().length()<1){
            result.put("mes","请输入真实的姓名！");
            result.put("status",0);
            return result;
        }

        //密码检查
        if(centerUser.getPassword()==null||centerUser.getPassword().length()<8||centerUser.getPassword().length()>16){
            result.put("mes","密码8-16位");
            result.put("status",0);
            return result;
        }
        String regex = "(\\w{3,10}\\.)*\\w+@\\w+(\\.\\w{2,3})*\\.\\w{2,3}";
        //邮箱检查
        if(centerUser.getEmail()==null||centerUser.getEmail().length()>50||!centerUser.getEmail().matches(regex)){
            result.put("mes","请输入真实的邮箱！");
            result.put("status",0);
            return result;
        }
        //社区检查
        ForumForum forumForum = ForumForumMapper.selectByPrimaryKey(centerUser.getForumId());
        if(forumForum==null){
            result.put("mes","社区不存在！");
            result.put("status",0);
            return result;
        }
        //证件检查
        if(centerUser.getCenterCredentialcode()==null||centerUser.getCenterCredentialcode().length()!=18){
            result.put("mes","证件应为18位！");
            result.put("status",0);
            return result;
        }
        //证件类型检查
        if(centerUser.getCenterUsertype()==null||centerUser.getCenterUsertype()<1||centerUser.getCenterUsertype()>3){
            result.put("mes","用户类型异常！");
            result.put("status",0);
            return result;
        }
        //证件资料
        if(centerUser.getCenterVerifydata()==null||centerUser.getCenterVerifydata().length()>255){
            result.put("mes","资料长度255以内！");
            result.put("status",0);
            return result;
        }
        try {
            //通过，注册用户
            //随机盐值
            String salt = KeyUtil.generateKey().substring(0, 5);
            //加密密码
            String passWard= new SimpleHash("MD5",centerUser.getPassword(),salt,2).toString();
            String id = KeyUtil.generateKey();
            CenterUser user=new CenterUser(id,centerUser.getName(),centerUser.getNickname(),
                    "","http://joylife-hello.oss-cn-chengdu.aliyuncs.com/joylife/97cc756c4d9a43559895282766a39853.jpg",centerUser.getForumId(),centerUser.getPhone(),passWard, UserConstant.REGISTRY_NOT_CREDENTIAL,centerUser.getCenterCredentialcode()
                    ,centerUser.getCenterVerifydata(),centerUser.getCenterUsertype(),new Date(),new Date(),centerUser.getEmail(),0,salt);
            centerUserMapper.insert(user);
            result.put("mes","注册成功");
            result.put("status",1);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("mes","系统维护中，请稍后！");
            result.put("status",0);
            return result;
        }
    }
    /*
    修改密码
     */
    @Override
    public Map<String, Object> alterPassService(String userId, String password, String newpass) {
        CenterUser centerUser = centerUserMapper.selectByPrimaryKey(userId);
        Map<String,Object>result=new HashMap<>();
        result.put("code",200);
        //用户输入检查
        if(password==null||password.length()<8||password.length()>16){
            result.put("status",0);
            result.put("mes","原始密码长度8-16位");
            return result;
        }
        if(newpass==null||newpass.length()<8||newpass.length()>16){
            result.put("status",0);
            result.put("mes","新密码长度8-16位");
            return result;
        }
        //原密码加密
        Object salt=centerUser.getSalt();
        String oldPass=new SimpleHash("MD5",password,salt,2).toString();
        if(oldPass.equals(centerUser.getPassword())){
            //密码正确，修改密码
            newpass=new SimpleHash("MD5",newpass,salt,2).toString();
            centerUser.setPassword(newpass);
            centerUserMapper.updateByPrimaryKey(centerUser);
            result.put("status",1);
            result.put("mes","修改成功");
            return result;
        }else{
            result.put("status",0);
            result.put("mes","密码错误");
            return result;
        }
    }
    /*
    用户退出登录
     */
    @Override
    public Map<String, Object> logoutService(String refreshtoken) {
        Map<Object, Object> hmget = redisUtil.hmget(refreshtoken);
        Map<String,Object>result=new HashMap<>();
        result.put("code",200);
        if(hmget!=null&&hmget.size()!=0){
            redisUtil.del(refreshtoken);
            result.put("status",1);
            result.put("mes","已退出");
        }else{
            result.put("status",0);
            result.put("mes","用户不存在");
        }
        return result;
    }
}
